package com.cloudm.technician.ui.modules.common.home

import com.cloudm.technician.data.config.Config
import com.cloudm.technician.data.model.VersionInfo
import com.cloudm.technician.data.network.CommonApi
import com.cloudm.technician.extensions.compareVersion
import com.cloudm.technician.extensions.isLicense
import com.cloudm.technician.extensions.isSnCode
import com.cloudm.technician.extensions.logger
import com.cloudm.technician.ui.base.RxPresenter

/**
 * 作者: wesley
 * 时间: 2017/12/18
 * 描述: 首页的业务逻辑
 */
class HomePresenter(private val view: HomeContract.View, private val commonApi: CommonApi) :
        RxPresenter(), HomeContract.Presenter {

    override fun checkVersion(versionName: String) {
        request(commonApi.checkVersion(versionName), view, onSuccess = { info, _ ->
            when (info) {
                null -> logger(" versionInfo is null")
                else -> view.checkVersionSuccess(info)
            }
        }, onFailure = { errorMsg ->
            logger(errorMsg)
        })
    }

    override fun checkShouldUpdate(info: VersionInfo, versionName: String) {
        when (info.compareVersion(versionName)) {
            -1 -> view.showUpdateDialog(info)
            else -> logger(" 当前已是最新版本 versionName = $versionName info = $info")
        }
    }


    override fun dealWithScanResult(value: String?) {
        if (value == null || value.isNullOrEmpty()) {
            view.showScanResultEmpMsg()
            return
        }
        val license = when (value.contains(Config.LICENSE_PREFIX)) {
            true -> value.substringAfterLast(Config.LICENSE_PREFIX)
            else -> value
        }

        when (license.isLicense()) {
            false -> {
                when (license.isSnCode()) {
                    false -> view.showLicenseFormatMsg()
                    else -> view.showRightLicense(license)
                }
            }
            else -> view.showRightLicense(license)
        }
    }

}